package entry;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import storage.bean.Storage;
import storage.dao.StorageMapper;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

@MultipartConfig
@WebServlet(value = "/getpic",loadOnStartup = 1)
public class GetPic extends HttpServlet {
    SqlSessionFactory sqlSessionFactory;
    @Override
    public void init() throws ServletException {
        try {
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(new InputStreamReader(Resources.getResourceAsStream("my_batis.xml")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //在这里获取图片存储的path，并放到context里面
        //累，，，咋获得context来着？
        ServletContext servletContext = getServletContext();
        Properties properties=new Properties();
        try {
            properties.load(Resources.getResourceAsStream("util.properties"));
            servletContext.setAttribute("picPath",properties.get("picPath"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //post请求，这里接收到了参数
        Part pic=req.getPart("pic");

        //把图片存入本地
        String key=picSaveInLocal(pic);


        //然后获取对应数据存入数据库
        Storage storage=savePicMsgIntoDb(pic,key);

        //然后把数据返回
        handelResp(resp,storage);

    }

    private void handelResp(HttpServletResponse resp,Storage storage) throws IOException {
        Back<Storage> back=new Back<>(0,storage,"成功");
        resp.getWriter().println(new ObjectMapper().writeValueAsString(back));
    }

    private Storage savePicMsgIntoDb(Part pic,String key){
        String fileRealName=key+"."+pic.getSubmittedFileName().split("\\.")[1];
        Storage storage=new Storage();
        storage.setKey(key);
        storage.setName(pic.getSubmittedFileName());
        storage.setType(pic.getContentType());
        storage.setSize(pic.getSize());
        storage.setUrl("http://localhost:8088/www/pic/"+fileRealName);
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        storage.setDeleted(0);

        SqlSession sqlSession=sqlSessionFactory.openSession();
        StorageMapper storageMapper=sqlSession.getMapper(StorageMapper.class);
        int result=storageMapper.addMarketStorage(storage);
        sqlSession.commit();

        System.out.println("更新了"+result+"条结果");

        return storage;

    }

    private String picSaveInLocal(Part pic) throws IOException {
        String key=UUID.randomUUID().toString();
        String filename= key+"."+pic.getSubmittedFileName().split("\\.")[1];
        //然后通过part获取对应的流哈
        InputStream inputStream=pic.getInputStream();
        //然后写输出流输出数据哈
        byte[] bytes=new byte[1024];
        OutputStream outputStream=new FileOutputStream(new File((String) getServletContext().getAttribute("picPath"),filename));

        //然后写入
        int bufReader=0;
        while ((bufReader=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,bufReader);
        }

        inputStream.close();
        outputStream.close();

        return key;
    }
}
